<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas 绘制渐变</title>
    <style>
      body{
        background: #666;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      canvas{
        background: #fff;
      }
      h1{
        color: #fff;
        font-size: 24px;
      }
    </style>
</head>
<body>
    <h1>渐变</h1>
    <canvas id="drawing" width="500" height="500" ></canvas>
    <script>
        /** @type {HTMLCanvasElement} */
        var drawing = document.getElementById('drawing')
        if (drawing.getContext) {
          const ctx = drawing.getContext('2d');
          
          const drawTable = () => {
            for (let i = 0; i < drawing.width / 10; i++) {
              let speed = 20;
              ctx.beginPath();
              // row
              ctx.moveTo(0, i * speed);             //创建一个起点
              ctx.lineTo(drawing.width, i * speed);
              // column
              ctx.moveTo(i * speed, 0);
              ctx.lineTo(i * speed, drawing.height);
              ctx.strokeStyle = 'rgba(0,0,0,.2)';
              ctx.stroke();
              ctx.closePath();
            }
          }
          drawTable()

          // 线性渐变
          let gradint = ctx.createLinearGradient(50,50, 100, 100)
          gradint.addColorStop(0, 'red')
          gradint.addColorStop(1, 'yellow')

          ctx.fillStyle = gradint
          ctx.fillRect(20,20, 150, 150)
          /*
            绘制矩形相当于在整个渐变图形中剪切出一部分来
            所以我们绘制矩形的坐标和尺寸必须要和渐变过度的部分重合
            不然我们就看不到渐变的内容了
          */

          // 经向渐变
          gradint = ctx.createRadialGradient(
            250, 250, 100,
            200, 200, 200
          )
          /*
            经向渐变结束6个值
            前3个是坐标和半径: 这是设置第一个渐变点的位置和范围
            后3个也是坐标和半径: 这是设置第二个渐变的颜色和范围
          */


          gradint.addColorStop(0, 'red')
          gradint.addColorStop(1, 'black')
          ctx.fillStyle = gradint
          ctx.fillRect(50, 50, 400, 400)

         }
    </script>
</body>
</html>
